﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SillyFactsWeb.Pages
{
    public partial class Default : System.Web.UI.Page
    {
        string hostAccessToken;
        Uri hostUrl;

        private Uri appWebUrl;
        private string appWebAccessToken;
        private SharePointContextToken spContextToken;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            TokenHelper.TrustAllCertificates();
            string contextToken = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextToken != null)
            {
                // Get context token
                spContextToken = TokenHelper.ReadAndValidateContextToken(contextToken, Request.Url.Authority);

                // Get host web access token
                hostUrl = new Uri(Request.QueryString["SPHostUrl"]);
                hostAccessToken = TokenHelper.GetAccessToken(spContextToken, hostUrl.Authority).AccessToken;

                // Get app web access token
                appWebUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
                appWebAccessToken = TokenHelper.GetAccessToken(spContextToken, appWebUrl.Authority).AccessToken;

                // Pass the access token to the button event handler.
                Button1.CommandArgument = string.Format("{0};{1}", hostAccessToken, appWebAccessToken);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            // Get Facts from Host web
            string hostAccessToken = ((Button)sender).CommandArgument.Split(';')[0];
            hostUrl = new Uri(Request.QueryString["SPHostUrl"]);
            List<string> facts = Facts.GetSillyFacts(hostUrl, hostAccessToken);

            // Display facts on page
            Literal1.Text = "<ul>";
            foreach (string fact in facts)
                Literal1.Text += string.Format("<li>{0}</li>", fact);
            Literal1.Text += "</ul>";

            // Add facts to Facts list in App web
            string appWebAccessToken = ((Button)sender).CommandArgument.Split(';')[1];
            appWebUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
            Facts.AddSillyFacts(facts, appWebUrl, appWebAccessToken);
        }

    }
}